﻿package handler

import (
	"net/http"
	v1 "server_go/api/v1" 
	"server_go/internal/service"
	"strconv" 

	"github.com/gin-gonic/gin"
)

type AdiminHandler struct {
	*Handler
	adiminService service.AdiminService
}

func NewAdiminHandler(
	handler *Handler,
	adiminService service.AdiminService,
) *AdiminHandler {
	return &AdiminHandler{
		Handler:       handler,
		adiminService: adiminService,
	}
}

func (h *AdiminHandler) Login(ctx *gin.Context) {
	req := new(v1.AdiminRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	token, err := h.adiminService.Login(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, v1.AdiminResponse{
		Token: token,
	})

}
func (h *AdiminHandler) CreateUser(ctx *gin.Context) {
	req := new(v1.AdiminCreateUserRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, 400, v1.ErrBadRequest, nil)
		return
	}
	if err := h.adiminService.CreateUser(ctx, *req); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	} else {
		v1.HandleSuccess(ctx, nil)
	}

}
func (h *AdiminHandler) DeleteUser(ctx *gin.Context) {
	userType := GetUserTypeFromCtx(ctx)
	if userType != 1 {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrTypeNotFound, nil)
		return
	}
	UserId := ctx.Param("userId")
	if UserId == "" {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrAdiminNotFound, gin.H{"error": "用户不存在"})
		return
	}
	userId, _ := strconv.Atoi(UserId)
	if err := h.adiminService.DeleteUser(ctx, uint(userId)); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

// 重置密码
func (h *AdiminHandler) ResetPassword(ctx *gin.Context) {
	UserId := ctx.Param("userId")
	if UserId == "" {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrAdiminNotFound, nil)
		return
	}
	req := new(v1.ResetPasswordRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	userId, _ := strconv.Atoi(UserId)
	err := h.adiminService.ResetPassword(ctx, *req, uint(userId))
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

// 查询所有用户
func (h *AdiminHandler) QueryAllUser(ctx *gin.Context) {
	userType := GetUserTypeFromCtx(ctx)
	if userType != 1 {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrTypeNotFound, nil)
		return
	}
	users, err := h.adiminService.QueryAllUser(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
	}
	v1.HandleSuccess(ctx, users)
}
